package kam_op

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"unsafe"
)

type RespData struct {
	Event string `json:"event"`
	Data string `json:"data"`
	Code int `json:"code"`
	Msg string `json:"msg"`
}

func getBaseUrl() string {
	if baseUrl := os.Getenv("BASE_URL"); baseUrl != "" {

		return baseUrl
	}

	return "http://localhost:8088"
}
func getUrl(path string, prefix string) string{
	// 声明字节缓冲
	var stringBuilder bytes.Buffer
	// 把字符串写入缓冲
	stringBuilder.WriteString(getBaseUrl())
	stringBuilder.WriteString(prefix)
	stringBuilder.WriteString(path)
	// 将缓冲以字符串形式输出
	return stringBuilder.String()
}

func SamplePost(path string, data map[string]string, prefix string) string{
	var url = getUrl(path, prefix)
	bytesData, err := json.Marshal(data)
	if err != nil {
		fmt.Println(err.Error() )
		return ""
	}
	reader := bytes.NewReader(bytesData)

	request, err := http.NewRequest("POST", url, reader)
	if err != nil {
		fmt.Println(err.Error())
		return ""
	}
	request.Header.Set("Content-Type", "application/json;charset=UTF-8")
	client := http.Client{}
	resp, err := client.Do(request)
	if err != nil {
		fmt.Println(err.Error())
		return ""
	}
	respBytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println(err.Error())
		return ""
	}
	//byte数组直接转成string，优化内存
	str := (*string)(unsafe.Pointer(&respBytes))
	fmt.Println(*str)
	return *str
}
